package com.example.personblog.repository;

import com.example.personblog.entity.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface CommentRepository extends JpaRepository<Comment, Long> {
    
    /**
     * 分页查询文章评论
     */
    Page<Comment> findByPostId(Long postId, Pageable pageable);
    
    /**
     * 获取用户的所有评论
     */
    List<Comment> findByUserIdOrderByCreateTimeDesc(Long userId);
    
    /**
     * 统计文章的评论数
     */
    Long countByPostId(Long postId);
    
    /**
     * 批量删除文章的所有评论
     */
    @Modifying
    @Transactional
    @Query("DELETE FROM Comment c WHERE c.postId = :postId")
    void deleteByPostId(@Param("postId") Long postId);
    
    /**
     * 检查评论是否属于指定用户
     */
    boolean existsByIdAndUserId(Long id, Long userId);
    
    /**
     * 获取最新的评论列表
     */
    @Query("SELECT c FROM Comment c ORDER BY c.createTime DESC")
    List<Comment> findLatestComments(Pageable pageable);
    
    /**
     * 分页查询用户评论
     */
    Page<Comment> findByUserId(Long userId, Pageable pageable);
    
    /**
     * 获取最新评论（带用户信息）
     */
    @Query("SELECT c FROM Comment c LEFT JOIN FETCH c.user ORDER BY c.createTime DESC")
    List<Comment> findLatestCommentsWithUser(Pageable pageable);
    
    /**
     * 增加点赞数
     */
    @Modifying
    @Transactional
    @Query("UPDATE Comment c SET c.likes = c.likes + 1 WHERE c.id = :id")
    void incrementLikes(@Param("id") Long id);
    
    /**
     * 减少点赞数
     */
    @Modifying
    @Transactional
    @Query("UPDATE Comment c SET c.likes = c.likes - 1 WHERE c.id = :id AND c.likes > 0")
    void decrementLikes(@Param("id") Long id);
    
    /**
     * 更新点赞数
     */
    @Modifying
    @Transactional
    @Query("UPDATE Comment c SET c.likes = :likeCount WHERE c.id = :commentId")
    void updateLikeCount(@Param("commentId") Long commentId, @Param("likeCount") Long likeCount);
} 